package com.woniu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.entity.Good;
import com.woniu.entity.GoodSearchParam;
import com.woniu.entity.GoodType;
import com.woniu.mapper.GoodMapper;
import com.woniu.service.GoodService;
import com.woniu.util.PageData;
import com.woniu.util.ResData;
import com.woniu.util.ResEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodServiceImpl implements GoodService {
    @Autowired
    private GoodMapper goodMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public ResData<?> queryGoods(PageData<GoodSearchParam> pageData) {
        PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
        List<Good> goods = goodMapper.queryGoods(pageData.getParam());
        PageInfo pageInfo = new PageInfo(goods);
        return new ResData<>().ok(pageInfo);
    }

    @Override
    public ResData<?> addGood(Good good) {
        try {
            goodMapper.addGood(good);
            return new ResData<>().ok();
        } catch (Exception e) {
            return new ResData<>().fail(ResEnum.FAIL);
        }
    }

    @Override
    public ResData<?> updateGood(Integer goodId, Integer status) {
        try {
            goodMapper.updateGood(goodId,status);
            return new ResData<>().ok();
        } catch (Exception e) {
            return new ResData<>().fail(ResEnum.FAIL);
        }
    }

    @Override
    public ResData<?> deleteGood(List<Integer> ids) {
        try {
            goodMapper.deleteGood(ids);
            return new ResData<>().ok();
        } catch (Exception e) {
            return new ResData<>().fail(ResEnum.FAIL);
        }
    }

    @Override
    public ResData<?> queryAllGoodTypes() {
        List<GoodType> redisGoodTypes = (List<GoodType>) redisTemplate.opsForValue().get("good_types");
        if(redisGoodTypes!=null){
            return new ResData<>().ok(redisGoodTypes);
        }
        List<GoodType> goodTypes = goodMapper.queryAllGoodTypes();
        redisTemplate.opsForValue().set("good_types",goodTypes);
        return new ResData<>().ok(goodTypes);
    }
}
